// ------------------------------------------------------------------------------------------------------------------------
// Plemiona.pl 5.X Skrypt użytkowy
//
// Nazwa:      Menu prawego przycisku myszy na mapie wiosek
// Wersja:     3.0
// Autor:      szatdafakp (Forum Plemion)
// Dostosował: Lukasz032 (Plemiona Ś7)
//
// Tagi specjakne:
// Licencja:   Creative Commons Uznanie autorstwa - Brak komercyjnego zastosowania - Na tych samych warunkach 2.0 Polska
// Informacje: http://creativecommons.org/licenses/by-nc-sa/2.0/pl
// Support:    lvwnbrz@lykamspam.pl
//
// ------------------------------------------------------------------------------------------------------------------------
// ==UserScript==
// @name           Menu prawego przycisku myszy na mapie wiosek
// @namespace      http://code.google.com/p/plemiona-skrypty/
// @description    Menu prawego przycisku myszy na mapie wiosek
// @version        3.0
// @license        Creative Commons 2.0 BY-NC-SA (http://creativecommons.org/licenses/by-nc-sa/2.0/pl)
// @author         szatdafakp (Forum Plemion)
// @contributor    Lukasz032 (Plemiona Ś7)
// @include        http://pl*.plemiona.pl/*screen=map*
// ==/UserScript==
// ------------------------------------------------------------------------------------------------------------------------


if ((typeof unsafeWindow) == "undefined") {
	unsafeWindow = window;
}

var _contextDiv;
var ordersFilterEnabled = false;
var t = "";
unsafeWindow.mapScrolled = false;


unsafeWindow.onTableClick = function onTableClick(event) {
	if (event.button == 2 && unsafeWindow.mapScrolled) {
		init();
		if (navigator.appVersion.indexOf("MSIE")>-1) {
		  var target1 = event.srcElement;
		} else {
      var target1 = event.target;
    };
		if (target1.parentNode.nodeName == "A") {
			unsafeWindow.showMenu(event);
		}
	}
}

// Walidator uprawnień uruchamiania.... 
function getGameDoc() {
  	getdoc=window.document;
  	if(!getdoc.URL.match("game.php")){
  		for(zeilenNummer=0;zeilenNummer<window.frames.length;zeilenNummer++){
  			if(window.frames[zeilenNummer].document.URL.match("game.php")){
  				getdoc = window.frames[zeilenNummer].document;
	  		}
  		}
  	}
  	return getdoc;
}
var PA = false;
var doc = getGameDoc();
try {
var tables = doc.getElementsByTagName('table');
     for (var i=0; i<tables.length; i++) {
        if (tables[i].rows[0].id == 'menu_row2' && tables[i].rows[0].cells.length == 5 && tables[i].rows[0].cells[4].innerHTML.match(/villages.png/)) {
          PA = true;
        } else if (doc.getElementsByTagName("ul")[0].className=="menu nowrap quickbar") {
          PA = true;
        } else {
          PA = false;
        }
      }
} catch (evt) {};

function init() {
  if (!PA) {
   return false;
  };
	unsafeWindow.mapScrolled = false;
	var tables;
	var table;
	tables = doc.getElementsByTagName('table');
	for (i = 0; i < tables.length; i++) {
		if (tables[i].className == "map") {
			table = tables[i];
		}
	}
	

	
	var cells = table.getElementsByTagName('td');
	for (var i = 0; i < cells.length; i++) {
		cells[i].setAttribute("onmousedown", "showMenu(event)");
		cells[i].setAttribute("oncontextmenu", "return false");
	}
}


function getTid(tid) {
	return (tid ? "&t=" + tid.toString() : "");
}

unsafeWindow.openInBackground = function openInBackground(url) {	
	GM_openInTab(url);
}

unsafeWindow.openInForeground = function openInForeground(url) {
	document.location = url;
}

unsafeWindow.showMenu = function showMenu(event) {
 try {
  if (navigator.appVersion.indexOf("MSIE")>-1) {
    var target_prep = event.srcElement;
  } else {
    var target_prep = event.target;
  };
  if (target_prep.tagName != "A") {
    if (target_prep.tagName == "TD") {
      target_prep = target_prep.innerHTML;
    } else {
      target_prep = target_prep.parentNode;
    }
  };
  
  var link = target_prep.getAttribute("href");
  var target = target_prep.getAttribute("href").match(/id=(\d+)/)[1];

	if ((event.button == 2) && (link)) {
		var curVillagePattern = new RegExp( "village=[0-9]+");
		var curVillageId = curVillagePattern.exec(link);
		curVillageId = curVillageId.toString().substring(curVillageId.toString().indexOf("=") + 1);
		
		var tidPattern = new RegExp("t=[0-9]+");
		var tid = tidPattern.exec(document.URL);
		if (tid) {
			tid = tid.toString().substring(2);
		}

		var idx = link.lastIndexOf("=");
		var villageId = link.substr(idx + 1);

		var links = _contextDiv.getElementsByTagName('a');
		
		links[0].href = "game.php?village=" + target + "&screen=map" + getTid(tid);
		links[0].innerHTML = "Scentruj mapę ";
		links[0].setAttribute("onclick","openInForeground(this.href); return false;");
		links[1].href = "game.php?village=" + target + "&screen=map" + getTid(tid);
		links[1].innerHTML = "(+)";
		links[1].target="_blank";
		
		links[2].href="game.php?screen=place&mode=command&target="+villageId+"&village="+curVillageId + getTid(tid);
		links[2].innerHTML = "Wyślij wojska ";
		links[2].setAttribute("onclick","openInForeground(this.href); return false;");
		links[3].href="game.php?screen=place&mode=command&target="+villageId+"&village="+curVillageId + getTid(tid);
		links[3].innerHTML = "(+)";
		links[3].target="_blank";


		
		links[4].href="game.php?&screen=market&mode=send&target="+villageId+"&village="+curVillageId + getTid(tid);
		links[4].innerHTML = "Wyślij surowce ";
		links[4].setAttribute("onclick","openInForeground(this.href); return false;");
		links[5].href="game.php?&screen=market&mode=send&target="+villageId+"&village="+curVillageId + getTid(tid);
		links[5].innerHTML = "(+)";
		links[5].target="_blank";

		str = target_prep.parentNode.style.backgroundColor;
		str = str.replace(/rgb\(|\)/g, "").split(",");
		if ( (str[0] == 255 && str[1] == 255 && str[2] == 255) 
			|| (str[0] == 240 && str[1] == 200 && str[2] == 0) ) {
					
			links[6].href = "game.php?village="+villageId+"&screen=overview"+ getTid(tid);
			links[6].innerHTML = "Przegląd wioski ";
			links[6].setAttribute("onclick","openInForeground(this.href); return false;");
			links[7].href = "game.php?village="+villageId+"&screen=overview"+ getTid(tid);
			links[7].innerHTML = "(+)";
			links[7].target="_blank";

			_contextDiv.getElementsByTagName('li')[3].style.padding="3px";
			
			links[8].href="javascript:popup_scroll('groups.php?&mode=village&village_id="+villageId+ getTid(tid)+"',300,400)";
			links[8].innerHTML = "Opracuj grupę";
			_contextDiv.getElementsByTagName('li')[4].style.padding="3px";
			
		} else {
			links[6].innerHTML = "";
			links[7].innerHTML = "";
			_contextDiv.getElementsByTagName('li')[3].style.padding="0px";
			
			links[8].innerHTML = "";
			_contextDiv.getElementsByTagName('li')[4].style.padding="0px";
		}
		

		if (ordersFilterEnabled) {
			links[9].href = "game.php?screen=overview_villages&page=-1&group=0&mode=commands&type=attack&village="+curVillageId+ getTid(tid)+"&coords="+x+"|"+y;
			links[9].innerHTML = "Ataki na wioskę ";
			links[9].setAttribute("onclick","openInForeground(this.href); return false;");
			links[10].href = "game.php?screen=overview_villages&page=-1&group=0&mode=commands&type=attack&village="+curVillageId+ getTid(tid)+"&coords="+x+"|"+y;
			links[10].innerHTML = "(+)";
			links[10].setAttribute("onclick","openInBackground(this.href); return false;");

			
			links[11].href = "game.php?screen=overview_villages&page=-1&group=0&mode=commands&type=support&village="+curVillageId+ getTid(tid)+"&coords="+x+"|"+y;
			links[11].innerHTML = "Wsparcia do wioski ";
			links[11].setAttribute("onclick","openInForeground(this.href); return false;");
			links[12].href = "game.php?screen=overview_villages&page=-1&group=0&mode=commands&type=support&village="+curVillageId+ getTid(tid)+"&coords="+x+"|"+y;
			links[12].innerHTML = "(+)";
			links[12].setAttribute("onclick","openInBackground(this.href); return false;");
		}
		

		var scrollTop = document.body.scrollTop; 
		var scrollLeft =  document.body.scrollLeft;
		_contextDiv.style.left = event.clientX + scrollLeft + 5 +  'px';
		_contextDiv.style.top = event.clientY + scrollTop + 5 + 'px';
		_contextDiv.style.display = 'block';
	}
 } catch (evt) {};
}

unsafeWindow.hideMenu = function hideMenu(e) {
	var reltg = e.relatedTarget;

	while (reltg != null){
		if (reltg.id == "divContext"){return;}
		reltg = reltg.parentNode;
	}
	_contextDiv.style.display = "none";
}

function createContextMenu() {
	var div = document.createElement('div');
	div.setAttribute('id', 'divContext');
	div.setAttribute('oncontextmenu', "return event.target.getElementsByTagName('a')[0];");
	div.setAttribute('style', 'border:1px solid black; z-index:103;background-color: #F7EED3; position: absolute');
	if (navigator.appVersion.indexOf("MSIE")>-1) {
	  div.setAttribute('onmouseup', 'hideMenu(event)');
	} else {
    div.setAttribute('onmouseout', 'hideMenu(event)');
  }
	div.setAttribute('width', '0');
	div.setAttribute('height', '0');
	div.innerHTML = '<list id="menu" style="list-style-type:none; z-index:104">' +
	'<li style="padding:3px"><a></a> <a></a></li>' +
	'<li style="padding:3px"><a></a> <a></a></li>' +
	'<li style="padding:3px"><a></a> <a></a></li>' +
	'<li style="padding:3px"><a></a> <a></a></li>' + 
	'<li style="padding:3px"><a></a> </li>' + 
	(ordersFilterEnabled ? '<li style="padding:3px"><a/> <a/></li>' + '<li style="padding:3px"><a/> <a/></li>' : '') +
	'</div>';
//	alert(div.width);
	div.style.display = "none";
	return div;
}


function addScrollListeners() {
	var tables = doc.getElementsByTagName('table');
	var table;

	
	for (i = tables.length-1; i >= 0; i--) {
		if (tables[i].className == "map_container") {
			table = tables[i];
		}
	}
	table.setAttribute("onmousedown", "onTableClick(event);return true;");
	rows = table.getElementsByTagName('tr');
	var oldOnclick = rows[0].getElementsByTagName('td')[1].getAttribute("onclick");
	rows[0].getElementsByTagName('td')[1].setAttribute("onclick", "mapScrolled = true;"+oldOnclick);
	oldOnclick = rows[1].getElementsByTagName('td')[0].getAttribute("onclick");
	rows[1].getElementsByTagName('td')[0].setAttribute("onclick", "mapScrolled = true;"+oldOnclick);
	oldOnclick = rows[1].getElementsByTagName('td')[rows[1].getElementsByTagName('td').length-1].getAttribute("onclick");
	rows[1].getElementsByTagName('td')[rows[1].getElementsByTagName('td').length-1].setAttribute("onclick", "mapScrolled = true;"+oldOnclick);
	oldOnclick = rows[rows.length-1].getElementsByTagName('td')[1].getAttribute("onclick");
	rows[rows.length-1].getElementsByTagName('td')[1].setAttribute("onclick", "mapScrolled = true;"+oldOnclick);
}


_contextDiv = createContextMenu();
doc.getElementsByTagName('body')[0].appendChild(_contextDiv);
addScrollListeners();
init();
